package net.zjitc.controller;


import jakarta.servlet.http.HttpServletRequest;
import net.zjitc.utils.APIResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

/**
*@author:xuying
*@date:2024/12/25 16:19:54
*/


@RestController
@RequestMapping("admin/upload")
public class FileUploadController {


    private static final String UPLOAD_DIR = "uploads/";
    @Autowired
    HttpServletRequest request;

    private static final String filePath = System.getProperty("user.dir") + "/uploads";

    private static final String targetPath = System.getProperty("user.dir") + "/target/classes/static/uploads";

    private static final String[] types = {"admin_avatar", "category_picture", "goods_album", "goods_picture","goods_description"};

    public APIResponse<String> uploadFile(MultipartFile file,String type) {
        if (file.isEmpty()) {
           return  APIResponse.err("文件为空",null);
        }
        try {
            long currentTime = System.currentTimeMillis();
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + "/" + type);
            Path path2 = Paths.get(targetPath + "/" + type);
            // 创建上传目录（如果不存在）
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }
            if(!Files.exists(path2)){
                Files.createDirectories(path2);

            }
            path = Paths.get(filePath + "/" + type + "/" + currentTime + "-" + file.getOriginalFilename());
            path2 = Paths.get(targetPath + "/" + type + "/" + currentTime + "-" + file.getOriginalFilename());
            Files.write(path, bytes);
            Files.write(path2, bytes);
            return APIResponse.suc("上传成功",  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" +"uploads/" + type + "/" + currentTime + "-" + file.getOriginalFilename());
        }
        catch (IOException e) {
            e.printStackTrace();
            return APIResponse.err("上传失败", null );
        }
    }


    @PostMapping("/picture")
    public APIResponse<String> uploadPicture( MultipartFile file, String type) {
        if(Arrays.stream(types).anyMatch(Type -> Type.equals(type))){
            return uploadFile(file,type);
        }else {
            return APIResponse.err("图片类型错误",null);
        }
    }

}
